"""
主应用入口文件
脑波云端分析系统 - FastAPI + MNE + YASA 项目的启动入口
配置FastAPI应用、中间件、路由、云端数据处理等
使用uvicorn作为ASGI服务器运行应用
原理：作为应用的入口点，初始化所有组件并启动云端分析服务
"""

import os
import uvicorn
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from contextlib import asynccontextmanager

# 导入配置和组件
from app.config.settings import settings
from app.utils.response import error_response


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时执行
    print("正在启动应用...")
    
    
    yield
    
    # 关闭时执行
    print("正在关闭应用...")


# 创建FastAPI应用实例
app = FastAPI(
    title=settings.APP_NAME,
    version=settings.APP_VERSION,
    description="基于FastAPI + MNE + YASA的脑波云端分析系统",
    debug=settings.APP_DEBUG,
    lifespan=lifespan
)

# 配置CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.CORS_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


# 全局异常处理器
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    """全局异常处理"""
    print(f"全局异常: {exc}")
    return JSONResponse(
        status_code=500,
        content=error_response(
            message="服务器内部错误",
            code=500
        )
    )


# 422 请求体验证错误处理器
from fastapi.exceptions import RequestValidationError
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    """请求体验证错误处理"""
    
    # 打印到控制台以便调试
    print(f"\n=== 422 请求体验证错误 ===")
    print(f"请求URL: {request.url}")
    print(f"请求方法: {request.method}")
    print(f"错误详情:")
    
    # 构建清晰的错误信息
    validation_errors = []
    for i, error in enumerate(exc.errors(), 1):
        field_name = " -> ".join(str(loc) for loc in error["loc"] if loc != "body")
        error_type = error["type"]
        error_msg = error["msg"]
        input_value = error.get("input", "未提供")
        
        print(f"  错误 {i}:")
        print(f"    字段: {field_name}")
        print(f"    错误类型: {error_type}")
        print(f"    错误消息: {error_msg}")
        print(f"    输入值: {str(input_value)[:200]}{'...' if len(str(input_value)) > 200 else ''}")
        
        # 根据错误类型提供更清晰的说明
        if error_type == "missing":
            description = f"缺少必填字段 '{field_name}'"
        elif error_type == "type_error":
            expected_type = error_msg.split("expected ")[1] if "expected " in error_msg else "未知类型"
            description = f"字段 '{field_name}' 类型错误，期望: {expected_type}"
        elif error_type == "value_error":
            if "ensure this value is greater than or equal to" in error_msg:
                min_val = error_msg.split("ensure this value is greater than or equal to ")[1]
                description = f"字段 '{field_name}' 值太小，最小值应为: {min_val}"
            elif "ensure this value is less than or equal to" in error_msg:
                max_val = error_msg.split("ensure this value is less than or equal to ")[1]
                description = f"字段 '{field_name}' 值太大，最大值应为: {max_val}"
            elif "ensure this value has at least" in error_msg:
                min_items = error_msg.split("ensure this value has at least ")[1].split(" item")[0]
                description = f"字段 '{field_name}' 数组长度不足，至少需要: {min_items} 个元素"
            elif "ensure this value has at most" in error_msg:
                max_items = error_msg.split("ensure this value has at most ")[1].split(" item")[0]
                description = f"字段 '{field_name}' 数组长度超限，最多允许: {max_items} 个元素"
            elif "string too short" in error_msg:
                description = f"字段 '{field_name}' 字符串太短"
            else:
                description = f"字段 '{field_name}' 值验证失败: {error_msg}"
        else:
            description = f"字段 '{field_name}' 验证失败: {error_msg}"
        
        validation_errors.append({
            "字段": field_name,
            "问题": description,
            "错误类型": error_type
        })
    
    print(f"=== 错误处理完成 ===\n")
    
    return JSONResponse(
        status_code=422,
        content={
            "success": False,
            "message": "请求体校验失败",
            "code": 422,
            "validation_errors": validation_errors,
            "总结": f"发现 {len(validation_errors)} 个校验错误，请检查以上字段"
        }
    )


# 注册路由
from app.controller.tablet_controller import tablet_router
from app.controller.cloud_storage_controller import cloud_storage_router
app.include_router(tablet_router, prefix=settings.API_V1_PREFIX)
app.include_router(cloud_storage_router, prefix=settings.API_V1_PREFIX)



# 根路径
@app.get("/")
async def root():
    """根路径"""
    return {
        "message": f"欢迎使用 {settings.APP_NAME}",
        "version": settings.APP_VERSION,
        "docs": "/docs",
        "redoc": "/redoc"
    }


# 健康检查
@app.get("/health")
async def health_check():
    """健康检查接口"""
    return {
        "status": "healthy",
        "app_name": settings.APP_NAME,
        "version": settings.APP_VERSION
    }


# 主函数
if __name__ == "__main__":
    # 创建日志目录
    os.makedirs("logs", exist_ok=True)
    
    # 启动应用
    uvicorn.run(
        "main:app",
        host=settings.APP_HOST,
        port=settings.APP_PORT,
        reload=settings.APP_DEBUG,
        log_level=settings.LOG_LEVEL.lower()
    )